package jlts.server;

import jlts.entity.Request;
import jlts.entity.Response;
import jlts.entity.User;

import java.io.*;
import java.lang.reflect.Method;
import java.net.Socket;

/**
 * @ClassName ServerThread
 * @Description TODO
 * @Author Zxeao
 * @Date 2021/12/23 下午5:10
 * @Version V1.0
 */
public class ServerThread extends Thread{
    private Socket client;

    /**封装了从文件获取用户信息到内存的逻辑，提供了根据用户名和密码找用户的操作*/
    private UserDao userDao=new UserDao();

    public ServerThread(Socket client) {
        this.client=client;
    }

    public User login(String uname,String upwd){
        System.out.println("!!!"+uname);
        //去数据库或者文件找用户并返回
        User u=userDao.getUser(uname,upwd);;
        return u;
    }

    @Override
    public void run() {
        while(true){
            try {
                InputStream is=client.getInputStream();
                ObjectInputStream ois=new ObjectInputStream(is);
                Request request=(Request)ois.readObject();

                System.out.println("正在解析来自客户端的请求");
                //解析Request
                String methodName=request.getMethod();
                Class[] paramTypes=request.getParamTypes();
                Object[] values=request.getValues();

                //利用反射原理 自动动态的调用某个方法
                Method method=this.getClass().getDeclaredMethod(methodName, paramTypes);
                // 自动调用某个方法，相当于this.login(uname,upwd);
                User u=(User)method.invoke(this, values);

                Response response=new Response();
                response.setValue(u);
                OutputStream os=client.getOutputStream();
                ObjectOutputStream oos=new ObjectOutputStream(os);
                oos.writeObject(response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
